<template>
  <a-card :bordered="false" :class="'cust-erp-sub-tab'">
    <!-- 操作按钮区域 -->
    <div class="table-operator" v-if="mainId">
      <a-button @click="handleAdd" type="primary" icon="plus" v-show="!isChecked && !productOrderId">新增</a-button>
      <a-button v-if="!editable" type="primary" icon="edit" @click="handleEditBatch" v-show="!isChecked"
        >编辑全部数量
      </a-button>
      <a-button
        v-else
        type="primary"
        icon="save"
        style="background-color: #67c23a;border-color: #67c23a"
        @click="handleSaveBatch"
        >保存全部
      </a-button>
      <a-button
        v-if="editable"
        type="primary"
        icon="rollback"
        style="background-color: red;border-color: red"
        @click="handleCancel"
        >取消编辑
      </a-button>
      <a-button @click="openQuickInputModal" type="primary" icon="plus" v-show="!isChecked">快捷录入</a-button>
      <a-button @click="printAll" type="primary" icon="printer" v-show="!isChecked">全部打印</a-button>
      <!--      <a-button @click="printByWarehouse" type="primary" icon="printer" v-show='!isChecked'>按仓位打印</a-button>-->
      <a-dropdown v-if="selectedRowKeys.length > 0 && !isChecked">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel">
            <a-icon type="delete" />
            删除
          </a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px">
          批量操作
          <a-icon type="down" />
        </a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
        <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
        >项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :scroll="{ x: true }"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="false"
        :loading="loading"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        @change="handleTableChange"
      >
        <template slot="materialCode" slot-scope="text, record">
          <div>
            <HfMaterialSearchSelectTag
              v-if="record.editable"
              :data-url="url.materialList"
              v-model="record.materialCode"
              @change="onMaterialChange(arguments, record)"
            ></HfMaterialSearchSelectTag>
            <template v-else slot-scope="text, record">
              {{ record.materialCode }}
            </template>
          </div>
        </template>
        <template slot="number" slot-scope="text, record">
          <a-input-number v-model:value="record.actualInputNumber" v-if="record.editable"></a-input-number>
          <span v-else>{{ text }}</span>
        </template>
        <template slot="warehouse" slot-scope="text, record">
          <j-dict-select-tag
            v-model:value="record.warehouse"
            v-if="record.editable"
            dict-code="hf_warehouse,warehouse_name,id"
            @change="changWarehouse($event, record)"
            style="width: 100%;"
          ></j-dict-select-tag>
          <span v-else>{{ text }}</span>
        </template>
        <template slot="action" slot-scope="text, record">
          <div class="editable-row-operations" v-show="record.status !== 1">
            <a :disabled="!record.editable" @click="handleDelete(record.id)">删除</a>
          </div>
        </template>
      </a-table>
    </div>

    <hfProductionProductInputDetail-modal
      ref="modalForm"
      @ok="modalFormOk"
      :mainId="mainId"
    ></hfProductionProductInputDetail-modal>
    <ProductInQuickInput
      ref="quickInputModal"
      :source-id="mainId"
      :source-serial="sourceSerial"
      @success="() => loadData()"
    ></ProductInQuickInput>
  </a-card>
</template>

<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import HfProductionProductInputDetailModal from './modules/HfProductionProductInputDetailModal.vue'
import { HfIODetailMixin } from '@/mixins/HfIODetailMixin'
import { postAction, putAction } from '@api/manage'
import { ajaxGetDictItems } from '@api/api'
import HfMaterialSearchSelectTag from '@comp/HfManual/HfMaterialSearchSelectTag.vue'
import { objectMerge } from '@/utils/util'
import store from '@/store'
import ProductInQuickInput from '@views/production/modules/ProductInQuickInput.vue'

export default {
  name: 'HfProductionProductInputDetailList',
  mixins: [JeecgListMixin, HfIODetailMixin],
  components: { ProductInQuickInput, HfMaterialSearchSelectTag, HfProductionProductInputDetailModal },
  props: {
    mainId: {
      type: String,
      default: '',
      required: false
    },
    sourceSerial: {
      type: String,
      default: '',
      required: false
    },
    productOrderId: {
      type: String,
      default: '',
      required: false
    }
  },
  watch: {
    mainId: {
      immediate: true,
      handler(val) {
        if (!this.mainId) {
          this.clearList()
        } else {
          this.queryParam['sourceId'] = val
          this.loadData(1)
        }
      }
    }
  },
  data() {
    return {
      description: '产品入库管理页面',
      disableMixinCreated: true,
      isChecked: false,
      editable: false,
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '物料代码',
          align: 'center',
          dataIndex: 'materialCode',
          scopedSlots: { customRender: 'materialCode' }
        },
        {
          title: '物料名称',
          align: 'center',
          dataIndex: 'materialName'
        },
        {
          title: '规格型号',
          align: 'center',
          dataIndex: 'sap'
        },
        {
          title: '单位',
          align: 'center',
          dataIndex: 'unit_dictText'
        },
        {
          title: '物料类型',
          align: 'center',
          dataIndex: 'materialType_dictText'
        },
        {
          title: '发料仓库',
          align: 'center',
          dataIndex: 'warehouse_dictText',
          scopedSlots: { customRender: 'warehouse' }
        },
        {
          title: '计划生产数量',
          align: 'center',
          dataIndex: 'planProduceNumber'
        },
        {
          title: '应收数量',
          align: 'center',
          dataIndex: 'supposedInputNumber'
        },
        {
          title: '实收数量',
          align: 'center',
          dataIndex: 'actualInputNumber',
          scopedSlots: { customRender: 'number' }
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 147,
          scopedSlots: { customRender: 'action' }
        }
      ],
      url: {
        list: '/production/hfProductionProductInput/listHfProductionProductInputDetailByMainId',
        delete: '/production/hfProductionProductInput/deleteHfProductionProductInputDetail',
        deleteBatch: '/production/hfProductionProductInput/deleteBatchHfProductionProductInputDetail',
        exportXlsUrl: '/production/hfProductionProductInput/exportHfProductionProductInputDetail',
        importUrl: '/production/hfProductionProductInput/importHfProductionProductInputDetail',
        add: '/production/hfProductionProductInput/addHfProductionProductInputDetail',
        edit: '/production/hfProductionProductInput/editHfProductionProductInputDetail',
        editAll: '/production/hfProductionProductInput/editAllHfProductionProductInputDetail',
        printUrl: '/jmreport/view/1028868004587257856'
      }
    }
  },
  created() {},
  computed: {
    importExcelUrl() {
      return `${window._CONFIG['domianURL']}/${this.url.importUrl}/${this.mainId}`
    },
    printUrl: function() {
      return `${window._CONFIG['domianURL']}/${this.url.printUrl}`
    }
  },
  methods: {
    printAll() {
      window.open(`${this.printUrl}?id=${this.mainId}&token=${store.getters.token}`)
    },
    // printByWarehouse(){
    //   let warehouses = [...new Set(this.dataSource.map(item=>item.warehouse))]
    //   for (let warehouse of warehouses){
    //     window.open(`${this.printUrl}?id=${this.mainId}&warehouse=${warehouse}&token=${store.getters.token}`)
    //   }
    // },
    clearList() {
      this.dataSource = []
      this.selectedRowKeys = []
      this.ipagination.current = 1
    },
    save(record) {
      if (!record.actualInputNumber) {
        this.$message.error('请输入数量')
        return
      }
      let param = Object.assign({}, record)
      param['sourceId'] = this.mainId
      param['sourceSerial'] = this.sourceSerial
      this.loading = false
      if (param.add) {
        postAction(this.url.add, param)
          .then(res => {
            if (res.success) {
              this.$message.success(res.message)
              this.loadData()
            } else {
              this.$message.warning(res.message)
            }
          })
          .finally(() => {
            this.loading = true
          })
      } else {
        putAction(this.url.edit, param)
          .then(res => {
            if (res.success) {
              this.$message.success(res.message)
              this.loadData()
            } else {
              this.$message.warning(res.message)
            }
          })
          .finally(() => {
            this.loading = true
          })
      }
    },
    changWarehouse(warehouse, record) {
      const newData = [...this.dataSource]
      const target = this.dataSource.find(item => item.materialCode === record.materialCode)
      let dictOptions
      ajaxGetDictItems('hf_warehouse,warehouse_name,id', null).then(res => {
        if (res.success) {
          dictOptions = res.result
          target.warehouse_dictText = dictOptions.find(item => item.value === record.warehouse).text
          target.warehouse = warehouse
          this.dataSource = newData
        }
      })
    },
    onMaterialChange([value, data], record) {
      // 初始化数据
      objectMerge(record, data, ['id', 'createBy', 'createTime', 'updateBy', 'updateTime'])
      record.actualPikingNumber = 0.0
      record.planPickingNumber = 0.0
    },

    handleEditBatch() {
      if (this.dataSource.length === 0) {
        this.$message.warning('请先添加至少一条明细')
        return
      }
      this.editable = this.isEdit(true)
    },
    handleSaveBatch() {
      this.editable = this.isEdit(false)
      postAction(this.url.editAll, this.dataSource, { params: { sourceId: this.mainId } }).then(res => {
        if (res.success) {
          this.$message.success(res.message)
          this.loadData()
        } else {
          this.$message.error(res.message)
        }
      })
    },
    handleCancel() {
      this.loadData()
      this.editable = this.isEdit(false)
    },
    openQuickInputModal() {
      this.$refs.quickInputModal.visible = true
      let uniqueData = this.dataSource.reduce((acc, cur) => {
        if (acc.find(item => item.materialCode === cur.materialCode)) {
          return acc
        }
        acc.push(cur)
        return acc
      }, [])
      for (const cur of uniqueData) {
        const targetList = this.dataSource.filter(item2 => item2.materialCode === cur.materialCode)
        for (const target of targetList) {
          if (target['warehouse_dictText'] === '车间良品仓') {
            cur['goodId'] = target.id
          }
          if (target['warehouse_dictText'] === '车间不良品仓') {
            cur['defectiveId'] = target.id
          }
          if (target['warehouse_dictText'] === '车间报废仓') {
            cur['scrapId'] = target.id
          }
        }
      }

      this.$refs.quickInputModal.dataSource = uniqueData
    }
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>
